package cn.stylefeng.guns.modular.trc.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.tron.trident.core.ApiWrapper;
import org.tron.trident.core.contract.Contract;
import org.tron.trident.core.contract.Trc20Contract;

@Configuration
public class TrcConfig {

    @Autowired
    private TrcProperty trcProperty;

    public volatile static  ApiWrapper apiWrapper;





    public ApiWrapper getApiWrapper() {

        if(apiWrapper == null){
            //配置是否是测试链还是正式链
            if (trcProperty.getIsProd()) {
                // 正式环境需要到Tron申请一个apiKey进行使用
                apiWrapper =  ApiWrapper.ofMainnet(trcProperty.getPayPrivateKey(), trcProperty.getApiKey());
            } else {
                // 测试环境不需要apikey
                apiWrapper =  ApiWrapper.ofNile(trcProperty.getPayPrivateKey());
            }
        }else {

            if(apiWrapper.channel.isShutdown()){
                apiWrapper = null;
                apiWrapper = getApiWrapper();
            }

        }
        return apiWrapper;
    }

    public Contract getContract(ApiWrapper wrapper){
        return wrapper.getContract(trcProperty.getUsdtContarct());
    }



    public Trc20Contract getPayToken(ApiWrapper wrapper,Contract contract){
        return new Trc20Contract(contract, trcProperty.getPayAddress(), wrapper);
    }


    public Trc20Contract getUserToken(ApiWrapper wrapper,Contract contract,String address){
        return new Trc20Contract(contract,address, wrapper);
    }


    public ApiWrapper getFromWrapper(String fromPrivateKey) {


            //配置是否是测试链还是正式链
            if (trcProperty.getIsProd()) {
                // 正式环境需要到Tron申请一个apiKey进行使用
                return ApiWrapper.ofMainnet(fromPrivateKey, trcProperty.getApiKey());
            } else {
                // 测试环境不需要apikey
                return  ApiWrapper.ofNile(fromPrivateKey);
            }
        }


}
